import Vue from "vue";
import utils from "./utils.js";
import { qywxJssdk } from "./service.js";
import MYJSWX from "./libs/jweixin/index.js";

let jsApiList = [
  "selectEnterpriseContact",
  "scanQRCode",
  "startBeaconDiscovery",
  "onBeaconUpdate",
  "getBeacons",
  "openLocation",
  "getLocation",
];

let initWxJsdk = function (appid, url, ready, myApiList) {
  let sessionValue = "";
  if (myApiList && myApiList.length > 0) {
    sessionValue = url + window.btoa(myApiList);
  } else {
    sessionValue = url + window.btoa(jsApiList);
  }
  if (
    utils.getSession("jsdkUrl") &&
    utils.getSession("jsdkUrl") == sessionValue
  ) {
    MYJSWX.ready(ready);
    return;
  }
  qywxJssdk({ url }, function (res) {
    if (res && res.data.code == 200) {
      utils.setSession("jsdkUrl", sessionValue);
      let wxParams = res.data.data;
      MYJSWX.config({
        beta: true, //invoke
        appId: appid, // 必填，公众号的唯一标识
        timestamp: wxParams.timeStamp, // 必填，生成签名的时间戳
        nonceStr: wxParams.nonce, // 必填，生成签名的随机串
        signature: wxParams.signature, // 必填，签名
        jsApiList: myApiList && myApiList.length ? myApiList : jsApiList, // 必填，需要使用的JS接口列表
      });
      MYJSWX.ready(ready);
      MYJSWX.error(function (res) {
        if (res.errMsg.indexOf("signature") > 0) {
          alert(JSON.stringify(res));
        }
      });
      Vue.prototype.$wx = MYJSWX;
    }
  });
};

export default {
  initWxJsdk,
};
